#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

char buf[500000];

void set_fl(int fd, int flags)
{
    int val;

    if ((val = fcntl(fd, F_GETFL, 0)) < 0)
    {
        perror("fcntl get fl error");
        exit(0);
    }

    val |= flags;

    if (fcntl(fd, F_SETFL, val) < 0)
    {
        perror("fcntl set fl error");
        exit(0);
    }
}

void clr_fl(int fd, int flags)
{
    int val;

    if ((val = fcntl(fd, F_GETFL, 0)) < 0)
    {
        perror("fcntl get fl error");
        exit(0);
    }

    val &= ~flags;

    if (fcntl(fd, F_SETFL, val) < 0)
    {
        perror("fcntl set fl error");
        exit(0);
    }
}

int main(int argc, char const* argv[])
{
    int ntowrite, nwrite;
    char *ptr;

    ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
    fprintf(stderr, "read %d bytes\n", ntowrite);

    /* set nonblocking */
    set_fl(STDOUT_FILENO, O_NONBLOCK);

    ptr = buf;
    while (ntowrite > 0)
    {
        errno = 0;
        nwrite = write(STDOUT_FILENO, ptr, ntowrite);
        fprintf(stderr, "nwrite=%d, errno=%d\n", nwrite, errno);

        if (nwrite > 0)
        {
            ptr += nwrite;
            ntowrite -= nwrite;
        }
    }
    
    /* clear nonblocking */
    clr_fl(STDOUT_FILENO, O_NONBLOCK);

    return 0;
}
